package me.miencraft.plugin.worldinfo;

import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.block.Biome;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.command.ConsoleCommandSender;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;
import org.jetbrains.annotations.NotNull;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public final class WorldInfo extends JavaPlugin {

    /**
     * 用于记录当前服务器是否为 1.16.4 或更高版本
     */
    public static final boolean IS_SERVER_AT_LEAST_1_16_4 = isServerVersionAtLeast("1.16.4");

    public static final Map<WeatherType, String> weatherMap = new HashMap<>();
    public static final Map<MoonPhase, String> moonPhaseMap = new HashMap<>();
    public static final Map<TimeType, String> timeMap = new HashMap<>();
    public static final Map<Biome, String> biomeMap = new HashMap<>();

    private static Placeholder placeholder;

    @Override
    public void onEnable() {
        // Plugin startup logic
        saveDefaultConfig();
        reloadConfig();

        getLogger().info("MC版本大于1.16.4: " + IS_SERVER_AT_LEAST_1_16_4);

        if (Bukkit.getPluginManager().getPlugin("PlaceholderAPI") != null) {
            placeholder = new Placeholder();
            placeholder.register();
            getLogger().info("已注册PlaceholderAPI扩展！");
        }

    }

    @Override
    public void onDisable() {
        if (placeholder != null) {
            placeholder.unregister();
        }
    }

    @Override
    public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) {
        if (args.length != 0) {
            String cmd = args[0];
            if (cmd.equalsIgnoreCase("reload")) {
                if (!sender.hasPermission("WorldInfo.command.reload")) {
                    sender.sendMessage("§c你没有权限执行此命令！");
                    return false;
                }
                reloadConfig();
                return true;
            }
            return false;
        }

        if (sender instanceof ConsoleCommandSender) {
            sender.sendMessage("/wi reload §7重载配置");
            return true;
        }

        Player player = (Player) sender;

        World world = player.getWorld();
        Location location = player.getLocation();

        long time = world.getTime();
        Biome biome = location.getBlock().getBiome();
        TimeType timeType = TimeType.fromGameTick((int) time);
        WeatherType weatherType = WeatherType.fromWorldWeather(world);
        int weatherDuration = WorldInfoUtil.getCurrentWeatherDuration(world);
        String formatWeatherDuration = WorldInfoUtil.formatTickToCustomString(weatherDuration, false);

        String weatherName = WorldInfoUtil.formatFrom(weatherType);
        String timeName = WorldInfoUtil.formatFrom(timeType);
        String biomeName = WorldInfoUtil.formatFrom(biome);
        String timeFormat = WorldInfoUtil.timeFormat(time);

        player.sendMessage("§a群系§f: " + biomeName + "§7[§f" + biome.name().toLowerCase() + "§7]");
        player.sendMessage("§e时间§f: " + timeName + "§7[§f" + timeFormat + "§7]");
        player.sendMessage("§6天气§f: " + weatherName + "§7[§f" + formatWeatherDuration + "§7]");

        return true;
    }

    @Override
    public List<String> onTabComplete(@NotNull CommandSender sender, @NotNull Command command, @NotNull String alias, @NotNull String[] args) {
        return Arrays.asList("time", "biome", "weather", "reload");
    }

    @Override
    public void reloadConfig() {
        super.reloadConfig();
        FileConfiguration config = getConfig();

        weatherMap.clear();
        ConfigurationSection weather = config.getConfigurationSection("weather");
        if (weather != null) {
            for (String key : weather.getKeys(false)) {
                try {
                    WeatherType type = WeatherType.valueOf(key.toUpperCase());
                    weatherMap.put(type, weather.getString(key));
                } catch (IllegalArgumentException e) {
                    getLogger().warning("Invalid weather type: " + key);
                }
            }
        }

        timeMap.clear();
        ConfigurationSection time = config.getConfigurationSection("time");
        if (time != null) {
            for (String key : time.getKeys(false)) {
                try {
                    TimeType type = TimeType.valueOf(key.toUpperCase());
                    timeMap.put(type, time.getString(key));
                } catch (IllegalArgumentException e) {
                    getLogger().warning("Invalid time type: " + key);
                }
            }
        }

        biomeMap.clear();
        ConfigurationSection biome = config.getConfigurationSection("biome");
        if (biome != null) {
            for (String key : biome.getKeys(false)) {
                try {
                    Biome type = Biome.valueOf(key.toUpperCase());
                    biomeMap.put(type, biome.getString(key));
                } catch (IllegalArgumentException e) {
                    getLogger().warning("Invalid biome type: " + key);
                }
            }
        }

        moonPhaseMap.clear();
        ConfigurationSection moonPhase = config.getConfigurationSection("moonPhase");
        if (moonPhase != null) {
            for (String key : moonPhase.getKeys(false)) {
                try {
                    MoonPhase phase = MoonPhase.valueOf(key);
                    String value = moonPhase.getString(key);
                    moonPhaseMap.put(phase, value);
                } catch (IllegalArgumentException ignored) {
                    getLogger().warning("Invalid moon phase type: " + key);
                }
            }
        }

    }

    /**
     * 检查当前服务器版本是否大于等于指定版本（如 "1.17"）
     *
     * @param version 要比较的目标版本号，例如 "1.17"
     * @return 如果当前版本 >= 目标版本，返回 true
     */
    public static boolean isServerVersionAtLeast(String version) {
        String serverVersion = Bukkit.getBukkitVersion().split("-")[0]; // 获取主版本号
        return compareVersions(serverVersion, version) >= 0;
    }

    /**
     * 比较两个版本号
     *
     * @param v1 版本号1（如 "1.16.4"）
     * @param v2 版本号2（如 "1.17"）
     * @return 0 表示相等，1 表示 v1 > v2，-1 表示 v1 < v2
     */
    private static int compareVersions(String v1, String v2) {
        String[] parts1 = v1.split("\\.");
        String[] parts2 = v2.split("\\.");

        int minLength = Math.min(parts1.length, parts2.length);
        for (int i = 0; i < minLength; i++) {
            int num1 = Integer.parseInt(parts1[i]);
            int num2 = Integer.parseInt(parts2[i]);
            if (num1 > num2) return 1;
            if (num1 < num2) return -1;
        }

        // 如果前面都相等，则长度更长的版本更大（如 1.17 > 1.17.0）
        return Integer.compare(parts1.length, parts2.length);
    }


}
